package com.gitee.linzl.zuul.gateway.fiters;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractDefaultFilter extends ZuulFilter {

	public void setFailedResponse(String body, int code) {
		log.debug("response error ({}): {}", code, body);
		RequestContext ctx = RequestContext.getCurrentContext();
		ctx.setResponseStatusCode(code);
		if (ctx.getResponseBody() == null) {
			ctx.addZuulResponseHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
			ctx.setResponseBody(body);
			ctx.setSendZuulResponse(false);// 终止请求的转发
			// throw new RuntimeException("Code: " + code + ", " + body); //optional
		}
	}

	public void setStaticResponse(String body, int code) {
		log.debug("response error ({}): {}", code, body);
		RequestContext ctx = RequestContext.getCurrentContext();
		ctx.setResponseStatusCode(code);
		if (ctx.getResponseBody() == null) {
			ctx.addZuulResponseHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML_VALUE);
			ctx.setResponseBody(body);
			ctx.setSendZuulResponse(false);// 终止请求的转发
			// throw new RuntimeException("Code: " + code + ", " + body); //optional
		}
	}

	public void setStaticResponse(InputStream is, int code) {
		RequestContext ctx = RequestContext.getCurrentContext();
		ctx.setResponseStatusCode(code);
		if (ctx.getResponseBody() == null) {
			ctx.addZuulResponseHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
			// ctx.setResponseDataStream(is);
			try {
				FileCopyUtils.copy(is, ctx.getResponse().getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			ctx.setSendZuulResponse(false);// 终止请求的转发
		}
	}
}
